package com.mms.utils;

import org.apache.commons.lang.StringUtils;
import org.springframework.util.Assert;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by dangz on 2017-5-22.
 */
public class CookieUtils {
    public CookieUtils() {
    }

    public static String getValue(HttpServletRequest request, String name) {
        Assert.notNull(request);
        Cookie cookie = getCookie(request, name);
        return cookie == null?null:cookie.getValue();
    }

    public static Cookie getCookie(HttpServletRequest request, String name) {
        Assert.notNull(request);
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0) {
            Cookie[] var6 = cookies;
            int var5 = cookies.length;

            for(int var4 = 0; var4 < var5; ++var4) {
                Cookie c = var6[var4];
                if(c.getName().equals(name)) {
                    return c;
                }
            }
        }

        return null;
    }

    public static String getCookieValue(HttpServletRequest request, String name) {
        Assert.notNull(request);
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0) {
            Cookie[] var6 = cookies;
            int var5 = cookies.length;

            for(int var4 = 0; var4 < var5; ++var4) {
                Cookie c = var6[var4];
                if(c.getName().equals(name)) {
                    return c.getValue();
                }
            }
        }

        return null;
    }

    public static Cookie addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, Integer expiry) {
        Cookie cookie = new Cookie(name, value);
        if(expiry != null) {
            cookie.setMaxAge(expiry.intValue());
        }

        String ctx = request.getContextPath();
        cookie.setPath(StringUtils.isBlank(ctx)?"/":ctx);
        response.addCookie(cookie);
        return cookie;
    }

    public static void cancleCookie(HttpServletRequest request, HttpServletResponse response, String name) {
        Cookie cookie = new Cookie(name, (String)null);
        cookie.setMaxAge(0);
        String ctx = request.getContextPath();
        cookie.setPath(StringUtils.isBlank(ctx)?"/":ctx);
        response.addCookie(cookie);
    }
}
